package org.mspring.mlog.security;

import javax.servlet.http.HttpServletRequest;

import org.mspring.mlog.entity.User;
import org.mspring.mlog.security.service.UserService;
import org.mspring.mlog.security.user.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Component;

/**
 *
 * @author Gao Youbo
 * @since 2014年10月13日
 */
@Component
public class SecurityService {

    private UserDetailsService userDetailsService;
    private UserService userService;

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    public User getCurrentUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(SecurityKeys.CURRENT_USER);
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param request
     */
    public User login(String username, String password, HttpServletRequest request) {
        User user = userService.login(username, password);
        if (user == null) {
            return null;
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
        User currentUser = ((UserDetailsImpl) userDetails).getUserEntity();
        request.getSession().setAttribute(SecurityKeys.CURRENT_USER, currentUser);
        return user;
    }

    /**
     * 登出
     *
     * @param request
     */
    public void logout(HttpServletRequest request) {
        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, null);
        request.getSession().setAttribute(SecurityKeys.CURRENT_USER, null);
        request.getSession().invalidate();
    }

    @Autowired
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
